//
//  ViewController.m
//  UI12_01_UITableView自定义Cell
//
//  Created by Scott on 16/3/24.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "ViewController.h"
#import "TableViewOfNews.h"
#import "JSONParser.h"
#import "ModelOfNews.h"
#import "CellOfNews.h"


@interface ViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) TableViewOfNews *tableView;

@property (nonatomic, retain) NSMutableArray *arrOfModel;


@end

@implementation ViewController

- (void)dealloc {
    
    [_tableView release];
    [_arrOfModel release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self handleData];
    
    [self createTableView];
    
    
}

#pragma mark - Data 
- (void)handleData {
    
    self.arrOfModel = [NSMutableArray array];
    
    id result = [JSONParser JSONParserWithFileName:@"news" type:@"txt"];
    
    NSArray *arrOfNews = [result objectForKey:@"news"];
    
    // 遍历数组
    for (NSDictionary *dic in arrOfNews) {
        
        ModelOfNews *model = [[ModelOfNews alloc] init];
        
        [model setValuesForKeysWithDictionary:dic];
        
        [self.arrOfModel addObject:model];
        
        [model release];
    }
    
}

#pragma mark - tableView
- (void)createTableView {
    
    self.tableView = [[TableViewOfNews alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    // 取消滚动条指示器
    self.tableView.showsVerticalScrollIndicator = NO;
    
    
#pragma mark - 知识点1: 自定义cell
    /** 详见CellOfNews类. */
    
    // 注册
    [self.tableView registerClass:[CellOfNews class] forCellReuseIdentifier:@"pool"];
 
}

#pragma mark - tableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrOfModel.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    CellOfNews *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    
    

    
    // 通过API赋值
    ModelOfNews *model = [self.arrOfModel objectAtIndex:indexPath.row];
    
    [cell setCellContentValues:model];

    
    // cell选中风格
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

/** 返回每行的高度. */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelOfNews *model = [self.arrOfModel objectAtIndex:indexPath.row];
    

    return [CellOfNews heightOfCellNews:model.summary];
    
}


#pragma mark - tableView Delegate


#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
